package concole;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class IOHelper {
	/**
	 * @author ljing12 This class now only has static methods and support the
	 *         I/O measure ;
	 */

	public static String readConsoleNextLine() {
		String returnStr = null;
		try {
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(System.in));
			returnStr = bufferedReader.readLine();
		} catch (Exception e) {
			System.out.println("SORRY some error happens");
		}
		return returnStr;
	}

	/**
	 * Used to write a string back to a file,pay attention that not add the
	 * file, but completely rewrite,may course data lose
	 * 
	 * @param fileName
	 * @param s
	 */

	public static void writeBackToFile(String fileName, String s) {
		try {
			FileWriter fileWriter = new FileWriter(fileName);
			BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
			bufferedWriter.write(s);
			bufferedWriter.close();
		} catch (Exception e) {
		}
	}

	/**
	 * Used to type all kinds of lists to Console
	 * 
	 * @param fileName
	 */
	public static void showAllFile(String fileName) {
		try {
			FileReader fileReader = new FileReader(fileName);
			BufferedReader bufferedReader = new BufferedReader(fileReader);
			String line = null;
			while ((line = bufferedReader.readLine()) != null) {
				System.out.println(line);
			}
			fileReader.close();
		} catch (Exception e) {
			System.out.println("sorry ERROR");
		}
	}

	public static String getAllFile(String fileName) {
		StringBuffer returnBuffer = new StringBuffer();

		try {
			FileReader fileReader = new FileReader(fileName);
			BufferedReader bufferedReader = new BufferedReader(fileReader);
			String line = null;
			int i = 1;
			while ((line = bufferedReader.readLine()) != null) {
				returnBuffer.append(i + ".");
				i++;
				returnBuffer.append(line);
				returnBuffer.append("\n");

				// System.out.println(line);
			}
			fileReader.close();

		} catch (Exception e) {
			System.out.println("sorry ERROR");
		} finally {
			return returnBuffer.toString().trim();
		}
	}

	/**
	 * Used to delete one line(according to the lineNumber) from certain file;
	 * 
	 * @param fileName
	 * @param num
	 */
	public static void deleteOneLine(String fileName, int num) {
		try {
			FileReader fileReader = new FileReader(fileName);
			BufferedReader bufferedReader = new BufferedReader(fileReader);
			StringBuffer strBF = new StringBuffer();
			String line = null;
			for (int i = 1; (line = bufferedReader.readLine()) != null; i++) {
				if (i != num) {
					strBF = strBF.append(line);
					strBF = strBF.append(System.getProperty("line.separator"));
				}
			}
			bufferedReader.close();
			PrintWriter printWriter = new PrintWriter(fileName);
			printWriter.write(strBF.toString());
			printWriter.close();
			System.out.println("Sucessfully deleted!");
		} catch (Exception e) {
			System.out.println("sorry ERROR");
		}
	}

	/**
	 * Used to delete oneLine that has two terms that matches all the two
	 * specific messages
	 * 
	 * @param fileName
	 * @param offSet1
	 * @param tag1
	 * @param offSet2
	 * @param tag2
	 */
	public static void deleteOneLine(String fileName, int offSet1, String tag1,
			int offSet2, String tag2) {
		try {
			FileReader fileReader = new FileReader(fileName);
			BufferedReader bufferedReader = new BufferedReader(fileReader);
			StringBuffer stringBuffer = new StringBuffer();
			String line = null;
			for (int i = 0; (line = bufferedReader.readLine()) != null; i++) {
				String[] strings = line.split(" ");
				if (!(strings[offSet1].equals(tag1) && strings[offSet2]
						.equals(tag2))) {
					stringBuffer.append(line);
					stringBuffer.append(System.getProperty("line.separator"));
				}
			}
			bufferedReader.close();
			PrintWriter printWriter = new PrintWriter(fileName);
			printWriter.write(stringBuffer.toString().trim());
			printWriter.close();
			System.out.println("Sucessfully delete the record");
		} catch (Exception e) {
			System.out
					.println("sorry error happens when delete one line frome the file");
		}
	}

	/**
	 * Used to the end of the file
	 * 
	 * @param fileName
	 * @param messageAdded
	 */
	public static void addOneLine(String fileName, String messageAdded) {

		try {
			FileReader fReader = new FileReader(fileName);
			BufferedReader bf = new BufferedReader(fReader);
			StringBuffer strBf = new StringBuffer();
			String record;
			while ((record = bf.readLine()) != null) {
				strBf.append(record);
				strBf.append(System.getProperty("line.separator"));
			}
			strBf.append(messageAdded);
			strBf.append(System.getProperty("line.separator"));
			bf.close();
			PrintWriter printWriter = new PrintWriter(fileName);
			printWriter.write(strBf.toString());
			printWriter.close();
			System.out.println("Sucessfully !");

		} catch (Exception e) {
			System.out.println("SOrry error happens");
		}

	}

	public static boolean ifExisted(int offSet, String fileName,
			String targetStr) {
		boolean ifExisted = false;
		try {
			FileReader fileReader = new FileReader(fileName);
			BufferedReader bufferedReader = new BufferedReader(fileReader);
			String line = null;
			for (int i = 1; (line = bufferedReader.readLine()) != null; i++) {
				String[] str = line.split(" ");
				if (str[offSet].equals(targetStr)) {
					ifExisted = true;
					break;
				}
			}

			bufferedReader.close();

		} catch (Exception e) {
			System.out.println("sorry ERROR");
		}
		return ifExisted;
	}

	/**
	 * 
	 * @param offSet
	 * @param fileName
	 * @param targetStr
	 * @return the first String in the file that contains the certain massage
	 */
	public static String findOneRecord(int offSet, String fileName,
			String targetStr) {
		String strReturn = null;
		try {
			FileReader fileReader = new FileReader(fileName);
			BufferedReader bufferedReader = new BufferedReader(fileReader);
			String line = null;
			for (int i = 1; (line = bufferedReader.readLine()) != null; i++) {
				String[] str = line.split(" ");
				if (str[offSet].equals(targetStr)) {
					strReturn = line;
					break;
				}
			}
			bufferedReader.close();
		} catch (Exception e) {
			System.out.println("sorry ERRORINFINDING");
		}

		return strReturn;
	}

	/**
	 * 
	 * @param offset1
	 * @param offset2
	 * @param fileName
	 * @param tag1
	 * @param tag2
	 * @return the first contains tag1 and tag2
	 */
	public static String findOneRecord(int offset1, int offset2,
			String fileName, String tag1, String tag2) {
		String strReturn = null;
		try {
			FileReader fileReader = new FileReader(fileName);
			BufferedReader bufferedReader = new BufferedReader(fileReader);
			String line = null;
			for (int i = 1; (line = bufferedReader.readLine()) != null; i++) {
				String[] str = line.split(" ");
				if (str[offset1].equals(tag1) && str[offset2].equals(tag2)) {
					strReturn = line;
					break;
				}
			}
			bufferedReader.close();
		} catch (Exception e) {
			System.out.println("sorry ERRORIN find the record!");
		}
		return strReturn;
	}

	/**
	 * 
	 * @param offset1
	 * @param offset2
	 * @param fileName
	 * @param targetStr1
	 * @param tag1
	 * @param tag2
	 * @return fine the line contains tag1 and tag2, and return the appointed
	 *         term by the backOffset
	 */
	public static String getOneTerm(int offset1, int offset2, String fileName,
			String targetStr1, String tag1, int tag2) {
		String strReturn = null;
		try {
			FileReader fileReader = new FileReader(fileName);
			BufferedReader bufferedReader = new BufferedReader(fileReader);
			String line = null;
			for (int i = 1; (line = bufferedReader.readLine()) != null; i++) {
				String[] str = line.split(" ");
				if (str[offset1].equals(targetStr1)
						&& str[offset2].equals(tag1)) {
					strReturn = line.split(" ")[tag2].trim();
					break;
				}
			}
			bufferedReader.close();
		} catch (Exception e) {
			System.out.println("sorry ERRORIN find the record!");
		}
		return strReturn;
	}

	/**
	 * Use new line to replace the old line
	 * 
	 * @param sourceStr
	 *            refers to the old line
	 * @param fileName
	 * @param targetStr
	 *            refers to the new line
	 */
	public static void replaceOneRecord(String fileName, String sourceStr,
			String targetStr) {
		try {
			FileReader fileReader = new FileReader(fileName);
			BufferedReader bufferedReader = new BufferedReader(fileReader);
			StringBuffer strBF = new StringBuffer();
			String line = null;
			for (int i = 1; (line = bufferedReader.readLine()) != null; i++) {
				if (!line.equals(sourceStr)) {
					strBF.append(line);
				} else {
					strBF.append(targetStr);
				}
				strBF.append(System.getProperty("line.separator"));
			}
			bufferedReader.close();
			PrintWriter printWriter = new PrintWriter(fileName);
			printWriter.write(strBF.toString());
			printWriter.close();
			System.out.println("Sucessfully replace the file!");

		} catch (Exception e) {
			System.out.println("sorry ERROR When replacing ");
		}
	}

	public static void addToLineEnd(String fileName, String keyToFindLine,
			int offSet, String addMessage) {

		try {
			FileReader fileReader = new FileReader(fileName);
			BufferedReader bufferedReader = new BufferedReader(fileReader);
			StringBuffer stringBuffer = new StringBuffer();
			String line = null;
			for (int i = 1; (line = bufferedReader.readLine()) != null; i++) {
				stringBuffer.append(line);
				String[] str = line.split(" ");
				if (str[offSet].equals(keyToFindLine)) {
					stringBuffer.append(" " + addMessage);

				}
				stringBuffer.append(System.getProperty("line.separator"));
			}
			PrintWriter printWriter = new PrintWriter(fileName);
			printWriter.write(stringBuffer.toString());
			printWriter.close();
			System.out.println("Sucessfully add to the line end!");
			bufferedReader.close();
		} catch (Exception e) {
			System.out.println("sorry ERRORIN adding to the line end");
		}

	}

	/**
	 * 
	 * @param fileName
	 * @param srcString
	 *            old term
	 * @param targetString
	 *            new term
	 * @param tag
	 * @param index
	 *            from the index to search
	 * @param tagOffset
	 */
	public static void replaceOneTermOfLine(String fileName, String srcString,
			String targetString, String tag, int index, int tagOffset) {

		try {
			FileReader fileReader = new FileReader(fileName);
			BufferedReader bufferedReader = new BufferedReader(fileReader);
			StringBuffer stringBuffer = new StringBuffer();
			String line = null;
			for (int i = 0; (line = bufferedReader.readLine()) != null; i++) {
				String[] str = line.split(" ");
				if (str[tagOffset].equals(tag)) {

					for (int j = 0; j < str.length; j++) {
						if (j >= index && str[j].equals(srcString)) {
							str[j] = targetString;
						}
						stringBuffer.append(str[j] + " ");
					}
					stringBuffer.deleteCharAt(stringBuffer.lastIndexOf(" "));
				} else {
					stringBuffer.append(line);
				}
				stringBuffer.append(System.getProperty("line.separator"));
			}
			PrintWriter printWriter = new PrintWriter(fileName);
			printWriter.write(stringBuffer.toString());
			printWriter.close();
			System.out.println("Sucessfully replace the term!");
			bufferedReader.close();
		} catch (Exception e) {
			System.out.println("sorry ERRORIN replacint the term");
		}

	}

	/**
	 * 
	 * @param fileName
	 * @param targetString
	 * @param tag
	 *            use tag to locate the line
	 * @param index
	 * @param tagOffSet
	 */
	public static void removeOneTermFromLine(String fileName,
			String targetString, String tag, int index, int tagOffset) {
		try {
			FileReader fileReader = new FileReader(fileName);
			BufferedReader bufferedReader = new BufferedReader(fileReader);
			StringBuffer stringBuffer = new StringBuffer();
			String line = null;
			for (int i = 0; (line = bufferedReader.readLine()) != null; i++) {
				String[] str = line.split(" ");
				if (str[tagOffset].equals(tag)) {

					for (int j = 0; j < str.length; j++) {
						if (j <= index || !str[j].equals(targetString)) {
							stringBuffer.append(str[j] + " ");
						}
					}
					stringBuffer.deleteCharAt(stringBuffer.lastIndexOf(" "));
				} else {
					stringBuffer.append(line);
				}
				stringBuffer.append(System.getProperty("line.separator"));
			}
			PrintWriter printWriter = new PrintWriter(fileName);
			printWriter.write(stringBuffer.toString());
			printWriter.close();
			System.out.println("Sucessfully remove the term!");
			bufferedReader.close();
		} catch (Exception e) {
			System.out.println("sorry ERRORIN removing the term");
		}
	}

	/**
	 * 
	 * @param offSet
	 * @param fileName
	 * @param targetStr
	 * @return All lines contains targetStr, and pay attention that the
	 *         returnString also use the "line.separator"
	 */
	public static String findAllMatchInfo(int offSet, String fileName,
			String targetStr) {
		String returnString = "";
		try {
			FileReader fileReader = new FileReader(fileName);
			BufferedReader bufferedReader = new BufferedReader(fileReader);
			String line = null;
			for (int i = 1; (line = bufferedReader.readLine()) != null; i++) {
				String[] str = line.split(" ");
				if (str[offSet].equals(targetStr)) {
					returnString += line;
					returnString += "\n";
				}
			}
			bufferedReader.close();
		} catch (Exception e) {
			System.out.println("sorry ERRORINFINDING");
		}
		return returnString.trim();
	}

	public static String findAllRegionMatches(int offSet, String fileName,
			String teacherNum) {
		String returnString = "";
		try {
			FileReader fileReader = new FileReader(fileName);
			BufferedReader bufferedReader = new BufferedReader(fileReader);
			String line = null;
			outter: for (int i = 1; (line = bufferedReader.readLine()) != null; i++) {
				String[] str = line.split(" ");
				str = str[offSet].split("&");
				for (int j = 0; j < str.length; j++) {
					if (str[j].equals(teacherNum)) {
						returnString += line;
						returnString += "\n";
						continue outter;
					}
				}
			}
			bufferedReader.close();
		} catch (Exception e) {
			System.out.println("sorry ERRORINFINDING");
		}

		return returnString.trim();
	}
	}
